package com.runfast.common.security.spring;

import com.runfast.common.dao.model.RunfastCuser;
import com.runfast.common.dao.model.RunfastCuserExample;
import com.runfast.common.service.RunfastCuserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Collections;
import java.util.List;

/**
 * @author: lijin
 * @date: 2018年06月01日
 */
public class DatabaseUserDetailService implements UserDetailsService {
    private RunfastCuserService cuserService;

    public DatabaseUserDetailService(RunfastCuserService cuserService) {
        this.cuserService = cuserService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        RunfastCuserExample cuserExample = new RunfastCuserExample();
        cuserExample.or().andMobileEqualTo(username);
        List<RunfastCuser> cusers = cuserService.selectByExample(cuserExample);
        if (cusers.isEmpty()) throw new UsernameNotFoundException("该用户不存在");
        RunfastCuser cuser = cusers.get(0);
        return new UserDataDetails<>(cuser.getMobile(), cuser.getPassword(), Collections.emptyList(), cuser);
    }
}
